import 'dart:async';
import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:proximity_sensor/proximity_sensor.dart';

class ProximityView extends StatefulWidget {
  @override
  _ProximityViewState createState() => _ProximityViewState();
}

class _ProximityViewState extends State<ProximityView> {
  // 记录点击和接近计数
  int _counter = 0;

  // 当前是否近距离
  bool _isNear = false;

  // 最近状态
  bool _isNearLast = false;

  // 最近变化时间
  DateTime _lastTime = DateTime.now();

  late StreamSubscription<dynamic> _streamSubscription;

  AudioPlayer audioPlugin = AudioPlayer();
  late String mp3Uri;

  /// 初始化进程
  @override
  void initState() {
    super.initState();
    listenSensor();
    _load();
  }

  /// 销毁进程
  @override
  void dispose() {
    super.dispose();
    _streamSubscription.cancel();
  }

  /// 距离传感器监视器
  Future<void> listenSensor() async {
    FlutterError.onError = (FlutterErrorDetails details) {
      if (foundation.kDebugMode) {
        FlutterError.dumpErrorToConsole(details);
      }
    };
    _streamSubscription = ProximitySensor.events.listen((int event) {
      setState(() {
        _isNear = (event > 0) ? true : false;
        _incrementCounterByProximity();
      });
    });
  }

  /// 距离传感器计数
  void _incrementCounterByProximity() {
    setState(() {
      DateTime now = DateTime.now();
      // 在上一次时间之后半秒
      if (_lastTime.add(Duration(milliseconds: 500)).isAfter(now)) {
        _lastTime = now;
      }
      // 上次为false，当前为true
      if (false == _isNearLast && true == _isNear) {
        _incrementCounter();
      }
      // 重置上次状态
      _isNearLast = _isNear;
    });
  }

  /// 通用计数
  void _incrementCounter() {
    setState(() {
      _counter++;
      _playSound();
    });
  }

  /// 提示音加载
  Future<Null> _load() async {
    final ByteData data = await rootBundle.load('assets/ding.wav');
    Directory tempDir = await getTemporaryDirectory();
    File tempFile = File('${tempDir.path}/ding.wav');
    await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
    mp3Uri = tempFile.uri.toString();
  }

  /// 播放提示音
  void _playSound() {
    audioPlugin.play(mp3Uri, isLocal: true);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '健身App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
          appBar: AppBar(
            title: const Text('健身App'),
          ),
          body: Center(
            child: Column(
              // 提示信息底部显示
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                SizedBox(
                  width: 220,
                  height: 220,
                  child: FloatingActionButton(
                    onPressed: _incrementCounter,
                    tooltip: 'Increment',
                    child: Icon(Icons.add),
                  ),
                ),
                SizedBox(
                  width: 100,
                  height: 200,
                ),
                Text(
                  '$_counter',
                  style: TextStyle(
                      fontSize: 26, color: _isNear ? Colors.red : Colors.black),
                ),
              ],
            ),
          )),
    );
  }
}
